import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { BillOfMaterialsDto } from '../../proxy/joy/erp/basic-archives/item-masters';
import { ItemMasterDto } from '../../proxy/joy/erp/basic-archives/item-masters/models';
import { ItemMasterService } from '../../proxy/joy/erp/basic-archives/item-masters/item-master.service';
import { ItemMasterRefSelectService } from '../../item-masters/item-master-ref-select/item-master-ref-select.services';
import { AuxiliaryUnitDto } from '../../proxy/joy/erp/basic-archives/item-masters/models';
import { UnitGroupService } from '../../proxy/joy/erp/basic-archives/item-masters/unit-group.service';
import { UnitGroupRefChildrenSelectService } from '../../item-masters/unit-group-ref-children-select/unit-group-ref-children-select.services';
import { Observable, map } from 'rxjs';

@Component({
  selector: 'lib-bill-of-materials-ref-entity',
  templateUrl: './bill-of-materials-ref-entity.component.html',
})
export class BillOfMaterialsRefEntityComponent implements OnInit {
  @Input() model: BillOfMaterialsDto;

  validateForm: FormGroup;
  
  
  showItemMasterSelect = (selectedItemMaster: ItemMasterDto) => {
    var modalRef = this.itemMasterRefSelectService.show(selectedItemMaster ? [selectedItemMaster] : [], { multiple: false });

    return modalRef.afterClose.pipe(
      map((selectedItemMasters: ItemMasterDto[]) => {
        if (selectedItemMasters && selectedItemMasters.length > 0) {
          return selectedItemMasters[0];
        }
        return null;
      })
    );
  }

  getItemMasterDetail = (itemMasterId: string) => {
    return this.itemMasterService.get(itemMasterId);
  }
  

  onItemMasterSelect = (itemMaster: ItemMasterDto) => {
    if (itemMaster) {
      this.validateForm.patchValue({
        itemCode: itemMaster.code,
        itemName: itemMaster.name,
        itemSpec: itemMaster.spec,
        unitGroupId: itemMaster.unitGroupId
      });

      // 如果计量单位为空，则获取料品计量单位组的主计量对应的 AuxiliaryUnit
      const currentUnitId = this.validateForm.get('unitId')?.value;
      if (!currentUnitId && itemMaster.unitGroup && itemMaster.unitGroup.children) {
        // 从 children 中找到 unitId 与 mainUnitId 相同的 AuxiliaryUnit
        const mainAuxiliaryUnit = itemMaster.unitGroup.children.find(
          child => child.unitId === itemMaster.unitGroup.mainUnitId
        );
        
        if (mainAuxiliaryUnit) {
          this.validateForm.patchValue({
            unitId: mainAuxiliaryUnit.id
          });
        }
      }
    }
  }

  getShowUnitSelect = (selectedUnit: AuxiliaryUnitDto) => {
    var modalRef = this.unitGroupRefChildrenSelectService.show(selectedUnit ? [selectedUnit] : [], { 
      multiple: false,
      unitGroupId: this.validateForm.value.unitGroupId
    });

    return modalRef.afterClose.pipe(
      map((selectedUnits: AuxiliaryUnitDto[]) => {
        if (selectedUnits && selectedUnits.length > 0) {
          return selectedUnits[0];
        }
        return null;
      })
    );
  }

  getUnitDetail = (unitId: string) => {
    return this.unitGroupService.getChild(unitId);
  }


  constructor(
    public fb: FormBuilder, public modalRef: NzModalRef,
    public itemMasterService: ItemMasterService,
    private itemMasterRefSelectService: ItemMasterRefSelectService,    
    private unitGroupService: UnitGroupService,
    private unitGroupRefChildrenSelectService: UnitGroupRefChildrenSelectService,
  ) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      //displayName: [this.model?.displayName, [Validators.required, Validators.maxLength(200)]],
      version: [this.model?.version, [Validators.required]],
      itemMasterId: [this.model?.itemMasterId, [Validators.required]],
      itemCode: [this.model?.itemCode, [Validators.required]],
      itemName: [this.model?.itemName, [Validators.required]],
      itemSpec: [this.model?.itemSpec],
      useCount: [this.model?.useCount, [Validators.required]],
      parentCount: [this.model?.parentCount, [Validators.required]],
      unitId: [this.model?.unitId, [Validators.required]],
      unitGroupId: [this.model?.itemMaster.unitGroupId]
    });
  }

  cancelForm() {
    this.modalRef.close(null);
  }

  submitForm() {
    if (!this.validateForm.valid) return;
    this.modalRef.close({
      ...this.model,
      ...this.validateForm.value,
    });
  }
}
